﻿using System;
using System.Collections.Generic;
using System.Linq;
using Common.util;
using Dapper;
using MySql.Data.MySqlClient;
using Spider.Mode;

namespace Common.Dao
{
    public class TradeDateDao
    {
        /// <summary>
        /// 返回n个交易日的开始和结束日期
        /// </summary>
        /// <returns>第一个元素：开始日期，第二个元素：结束日期</returns>
        public static List<DateTime> GetLastNBeginDateAndEndDateWithoutToday(int nDays, DateTime date)
        {
            var sql = "select trade_date FROM  tb_trade_dates " +
                      "where trade_date<@TradeDate order by trade_date desc" +
                      " limit @days ;";
            using (var conn = DbUtils.GetHotTopicConnection())
            {
                var result = conn.Query<DateTime>(sql, new {TradeDate = date, days = nDays+1})?.ToList();
                if (result == null || result.Count() != nDays+1)
                {
                    return null;
                }

                DateTime beginDateTime = result.Last();
                DateTime endDateTime = result.First();
                var beginAndendDateTime = new List<DateTime>();
                beginAndendDateTime.Add(beginDateTime);
                beginAndendDateTime.Add(endDateTime);
                return beginAndendDateTime;
            }
        }

        public static bool IsTradeDate(DateTime today)
        {
            var sql = "select trade_date FROM `tb_trade_dates` where trade_date = @Today";
            using (var conn = DbUtils.GetHotTopicConnection())
            {
                var result = conn.Query<DateTime>(sql, new {Today = today});
                return result.Any();
            }
        }

    }
}